package com.tang.controller;


import com.tang.dto.BookDTO;
import com.tang.dto.DocDTO;
import com.tang.dto.ImageDTO;
import com.tang.resp.JsonResp;
import com.tang.service.impl.DocServiceImpl;
import com.tang.service.impl.ImageServiceImpl;
import com.tang.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/image/*")
public class ImageController {

    @Autowired
    private ImageServiceImpl imageService;

    @PostMapping( "/upload")
    private Object postUserInforUpDate(HttpServletRequest request, @RequestParam("file") MultipartFile multipartFile) throws IOException {
        JsonResp resp = new JsonResp();
        // 用来获取其他参数
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        String name = params.getParameter("username");
        if (!multipartFile.isEmpty()) {
            resp.setCode(200);
            FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();
//            PictureUtil.getRandomFileName()
            String path = QiniuUtils.uploadQNImg(inputStream, name); // KeyUtil.genUniqueKey()生成图片的随机名
            System.out.print("七牛云返回的图片链接:" + path);
            ImageDTO dto = new ImageDTO();
            dto.setUrl(path);
            resp.setMessage("上传成功");
            resp.setData(imageService.add(dto));
            return resp;
        }
        resp.setCode(200);
        resp.setMessage("上传失败");
        return resp;
    }
    @GetMapping("all")
    public JsonResp all(){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        resp.setMessage("查询图片路径成功");
        List<ImageDTO> all = imageService.all();
        resp.setData(all);
        return resp;
    }
    @PostMapping ("add")
    public JsonResp add(ImageDTO imageDTO){
        JsonResp resp = new JsonResp();
        resp.setCode(200);
        resp.setMessage("增加图片路径成功");
        int i= imageService.add(imageDTO);
        resp.setData(i);
        return resp;
    }
}
